package com.lanren.familybookapp.ui.home.view;

import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hjq.toast.ToastUtils;
import com.lanren.common.interfaces.AdapterItemClickView;
import com.lanren.common.utils.DateUtils;
import com.lanren.common.utils.GsonUtils;
import com.lanren.common.utils.LogUtils;
import com.lanren.common.utils.StringUtils;
import com.lanren.common.utils.Utils;
import com.lanren.common.utils.event.C;
import com.lanren.common.widget.pickerview.TimePickerDialog;
import com.lanren.common.widget.pickerview.data.Type;
import com.lanren.common.widget.pickerview.listener.OnDateSetListener;
import com.lanren.common.widget.statusbar.ImmersionBar;
import com.lanren.easydialog.AnimatorHelper;
import com.lanren.easydialog.DialogViewHolder;
import com.lanren.easydialog.EasyDialog;
import com.lanren.easyeventbus.Event;
import com.lanren.familybookapp.R;
import com.lanren.familybookapp.app.AppUserHelper;
import com.lanren.familybookapp.base.BaseUiLazyFragment;
import com.lanren.familybookapp.helper.DialogHelper;
import com.lanren.familybookapp.ui.home.adapter.HomeBookAdapter;
import com.lanren.familybookapp.ui.home.bean.BookGroupBean;
import com.lanren.familybookapp.ui.home.bean.BookListBean;
import com.lanren.familybookapp.ui.home.interfaces.IHomeModel;
import com.lanren.familybookapp.ui.home.model.HomeModel;
import com.lanren.familybookapp.ui.home.presenter.HomePresenter;
import com.lanren.familybookapp.ui.me.bean.BookInfoBean;
import com.lanren.familybookapp.ui.me.view.BookEditActivity;
import com.lanren.familybookapp.ui.me.view.BookManagerActivity;
import com.lanren.hovertitlerecylerview.HoverTitleItemDecoration;
import com.lanren.hovertitlerecylerview.HoverTitleRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ClassName HomeFragment
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2019/10/5 16:53
 * @Version 1.0
 */
public class HomeFragment extends BaseUiLazyFragment<HomePresenter> implements IHomeModel.IHomeView {

    @BindView(R.id.book_title_txt)
    TextView bookTitleTxt;
    @BindView(R.id.book_more_img)
    ImageView bookMoreImg;
    @BindView(R.id.book_time)
    TextView bookTime;
    @BindView(R.id.book_xiala_img)
    ImageView bookXialaImg;
    @BindView(R.id.book_out_money)
    TextView bookOutMoney;
    @BindView(R.id.book_in_money)
    TextView bookInMoney;
    @BindView(R.id.book_budget_money)
    TextView bookBudgetMoney;
    @BindView(R.id.book_layout_view)
    RelativeLayout bookLayoutView;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.book_recycler_view)
    HoverTitleRecyclerView bookRecyclerView;
    @BindView(R.id.wb_refresh)
    SmartRefreshLayout wbRefresh;
    @BindView(R.id.book_add)
    ImageView bookAdd;
    @BindView(R.id.book_member)
    TextView bookMember;
    @BindView(R.id.book_member_xiala_img)
    ImageView bookMemberXialaImg;

    private TimePickerDialog mDialogYearMonth;

    private List<BookGroupBean> groupBeanList = new ArrayList<>();
    private HomeBookAdapter homeBookAdapter;

    private int page = 0;
    private boolean isRefresh = false;
    private String mBudget;//账本预算
    private String mInvite = "全部";


    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    public HomePresenter createPresenter() {
        return new HomePresenter(new HomeModel());
    }

    @Override
    protected void setStatusBar() {
        mImmersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    @Override
    protected void initFragment() {
        initView();
        initData();
        initEvent();
    }


    public void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        bookRecyclerView.setLayoutManager(layoutManager);

        mDialogYearMonth = new TimePickerDialog.Builder()
                .setThemeColor(getResources().getColor(R.color.green10))
                .setTitleStringId("选择时间")
                .setMinMillseconds(DateUtils.rollYear(new Date(), -20).getTime())
                .setMaxMillseconds(DateUtils.rollDay(new Date(), 7).getTime())
                .setCurrentMillseconds(DateUtils.getNowTime())
                .setType(Type.YEAR_MONTH)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        bookTime.setText(DateUtils.longToFormat(millseconds, "yyyy年MM月"));
                        wbRefresh.autoRefresh();
                    }
                })
                .setCyclic(false)
                .build();

        homeBookAdapter = new HomeBookAdapter(groupBeanList);
        bookRecyclerView.setAdapter(homeBookAdapter);
        bookRecyclerView.addItemDecoration(new HoverTitleItemDecoration());

    }

    @SuppressLint("SimpleDateFormat")
    public void initData() {
        bookMember.setText("全部");
        bookTime.setText(DateUtils.longToFormat(DateUtils.getNowTime(), "yyyy年MM月"));
        LogUtils.d("=========" + AppUserHelper.getInstance().getUser().getUserUseBook());
        mPresenter.getUserInfo();

    }


    public void initEvent() {

        bookRecyclerView.setmOnHoverTitleListener(new HoverTitleRecyclerView.OnHoverTitleListener() {
            @Override
            public void onHoverTitleClick(int adapterPosition) {

            }

            @Override
            public void onHoverTitleSelection(int adapterPosition) {

            }
        });

        bookRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy < 0) {//下滑
                    bookAdd.setVisibility(View.VISIBLE);
                } else if (dy > 0) {//上滑
                    bookAdd.setVisibility(View.GONE);
                }
            }
        });

        wbRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (AppUserHelper.getInstance().getUser().getUserUseBook() == 0) {
                    wbRefresh.finishRefresh();
                } else {
                    mPresenter.getBookInfo(AppUserHelper.getInstance().getUser().getUserUseBook());
                }
                getData(true);
            }
        });

        homeBookAdapter.setAdapterItemClickView(new AdapterItemClickView() {
            @Override
            public void onItemClick(int pointion) {
                BookkeepingInfoActivity.startActivity(getActivity(), groupBeanList.get(pointion));
            }

            @Override
            public void onItemClick(int pointion, View view) {

            }

            @Override
            public void onItemLongClick(int pointion) {

            }

            @Override
            public void onItemLongClick(int pointion, View view) {

            }
        });
    }

    @Override
    protected void onRestart() {

    }

    @Override
    protected boolean registEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case C.EventCode.REFRESH_HOME:
                wbRefresh.autoRefresh();
                break;
            case C.EventCode.REFRESH_HOME_UPDATE:
                BookGroupBean bookGroupBean = (BookGroupBean) event.getData();
                updateHomeBook(bookGroupBean);
                break;
            case C.EventCode.REFRESH_HOME_DEL_BOOK:
                BookGroupBean bookGroup = (BookGroupBean) event.getData();
                delHomeBook(bookGroup);
                break;
        }
    }

    private void updateHomeBook(BookGroupBean bookGroupBean) {
        for (int i = 0; i < groupBeanList.size(); i++) {
            if (groupBeanList.get(i).getBooksBeanList() != null) {
                if (bookGroupBean.getBooksBeanList().getId() == groupBeanList.get(i).getBooksBeanList().getId()) {
                    String oldTime = groupBeanList.get(i).getBookTime();
                    String newTime = bookGroupBean.getBookTime();
                    if (!oldTime.substring(0, 10).equals(newTime.substring(0, 10))) {
                        wbRefresh.autoRefresh();
                        return;
                    }

                    groupBeanList.get(i).setBookTime(bookGroupBean.getBookTime());
                    groupBeanList.get(i).getBooksBeanList().setInOut(bookGroupBean.getBooksBeanList().getInOut());
                    groupBeanList.get(i).getBooksBeanList().setBookClassify(bookGroupBean.getBooksBeanList().getBookClassify());
                    groupBeanList.get(i).getBooksBeanList().setMoney(bookGroupBean.getBooksBeanList().getMoney());
                    groupBeanList.get(i).getBooksBeanList().setGoods(bookGroupBean.getBooksBeanList().getGoods());
                    groupBeanList.get(i).getBooksBeanList().setBookMember(bookGroupBean.getBooksBeanList().getBookMember());
                    groupBeanList.get(i).getBooksBeanList().setPaymentType(bookGroupBean.getBooksBeanList().getPaymentType());
                    groupBeanList.get(i).getBooksBeanList().setPs(bookGroupBean.getBooksBeanList().getPs());

                    homeBookAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    private void delHomeBook(BookGroupBean bookGroupBean) {
        for (int i = 0; i < groupBeanList.size(); i++) {
            if (groupBeanList.get(i).getBooksBeanList() != null) {
                if (bookGroupBean.getBooksBeanList().getId() == groupBeanList.get(i).getBooksBeanList().getId()) {
                    groupBeanList.remove(i);
                    homeBookAdapter.notifyItemRemoved(i);
                    homeBookAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < groupBeanList.size(); i++) {
            if (bookGroupBean.getBookTime().substring(5, 10).equals(groupBeanList.get(i).getBookTime().substring(5, 10))) {
                list.add(i);
            }
        }
        if (list.size() == 1) {
            groupBeanList.remove(list.get(0).intValue());
            homeBookAdapter.notifyItemRemoved(list.get(0));
            homeBookAdapter.notifyDataSetChanged();
        }
    }

    private void getData(boolean refresh) {
        isRefresh = refresh;
        if (isRefresh) {
            page = 0;
        }
        page++;
        if (AppUserHelper.getInstance().getUser().getUserUseBook() == 0) {
            wbRefresh.finishRefresh();
        } else {
            if (mInvite.equals("全部")) {
                mInvite = "";
            }
            mPresenter.getBookList(AppUserHelper.getInstance().getUser().getUserUseBook(),
                    DateUtils.stringToFormat(bookTime.getText().toString()),
                    page, mInvite);
        }

        LogUtils.d("头部数据：" + GsonUtils.toJson(AppUserHelper.getHttpHeaders()));
    }

    @Override
    public void showError(int code, String msg) {
        if (code == 10003) {
            if (groupBeanList.size() == 0) {
                showEmpty();
                wbRefresh.finishRefresh();
                bookInMoney.setText("--");
                bookOutMoney.setText("--");
            } else {
                if (isRefresh) {
                    groupBeanList.clear();
                    homeBookAdapter.notifyDataSetChanged();
                    showEmpty();
                }
                wbRefresh.finishLoadMoreWithNoMoreData();
            }
        } else {
            wbRefresh.finishRefresh();
            wbRefresh.finishLoadMore();
            super.showError(code, msg);
        }
    }

    @Override
    public void onSuccess() {
        if (AppUserHelper.getInstance().getUser().getUserUseBook() == 0) {
            bookTitleTxt.setText("--");
            bookBudgetMoney.setText("--");
            bookInMoney.setText("--");
            bookOutMoney.setText("--");
            showLayout(getView(), R.mipmap.icon_hint_empty, R.string.home_hint_layout_no_bookkeeping);
        } else {
            showComplete();
            wbRefresh.autoRefresh();
        }
    }

    @Override
    public void onSuccess(List<BookListBean> bookListBeans) {
        if (bookListBeans.size() > 0) {
            if (isRefresh) {
                wbRefresh.finishRefresh();
                groupBeanList.clear();
            }
            showComplete();

            String imMoney = StringUtils.formatNum(bookListBeans.get(0).getPayInMoneyTotalMonthly());
            String outMoney = StringUtils.formatNum(bookListBeans.get(0).getPayOutMoneyTotalMonthly());
            bookInMoney.setText(StringUtils.replaceNullByPstr(imMoney, "--"));
            bookOutMoney.setText(StringUtils.replaceNullByPstr(outMoney, "--"));

            for (int i = 0; i < bookListBeans.size(); i++) {
                if (isRefresh) {
                    setGroupBeanListAll(i, bookListBeans);
                } else {
                    if (groupBeanList.size() > 0) {
                        boolean newFlag = false;
                        int index = 0;
                        String newTime = bookListBeans.get(i).getBookTime().substring(5, 10);
                        for (int q = 0; q < groupBeanList.size(); q++) {
                            if (newTime.equals(groupBeanList.get(q).getBookTime().substring(5, 10))) {
                                newFlag = true;
                                index = q + 1;
                                break;
                            }
                        }
                        if (newFlag) {
                            for (int j = 0; j < bookListBeans.get(i).getBooksBeanList().size(); j++) {
                                BookGroupBean bookGroupBean1 = new BookGroupBean();
                                bookGroupBean1.setGroup(false);
                                bookGroupBean1.setBookTime(bookListBeans.get(i).getBookTime());
                                bookGroupBean1.setBooksBeanList(bookListBeans.get(i).getBooksBeanList().get(j));
                                double inMoneyDay = groupBeanList.get(index - 1).getPayInMoneyDay();
                                double outMoneyDay = groupBeanList.get(index - 1).getPayOutMoneyDay();
                                if (bookListBeans.get(i).getBooksBeanList().get(j).getInOut().equals("支出")) {
                                    String money = StringUtils.formatDouble(outMoneyDay + bookListBeans.get(i).getBooksBeanList().get(j).getMoney(),
                                            "0.00");
                                    groupBeanList.get(index - 1).setPayOutMoneyDay(Double.valueOf(money));
                                } else if (bookListBeans.get(i).getBooksBeanList().get(j).getInOut().equals("收入")) {
                                    String money = StringUtils.formatDouble(inMoneyDay + bookListBeans.get(i).getBooksBeanList().get(j).getMoney(),
                                            "0.00");
                                    groupBeanList.get(index - 1).setPayInMoneyDay(Double.valueOf(money));
                                }
                                groupBeanList.add(index, bookGroupBean1);
                            }
                        } else {
                            setGroupBeanListAll(i, bookListBeans);
                        }
                    }
                }
            }
            if (isRefresh) {
                homeBookAdapter.notifyDataSetChanged();
            } else {
                wbRefresh.finishLoadMore();
                homeBookAdapter.notifyDataSetChanged();
//                homeBookAdapter.notifyItemRangeChanged(0, groupBeanList.size() - 1);
            }
        } else {
            if (groupBeanList.size() == 0) {
                showEmpty();
            } else {
                wbRefresh.finishLoadMoreWithNoMoreData();
            }
        }
    }

    private void setGroupBeanList(int i, List<BookListBean> bookListBeans) {
        for (int j = 0; j < bookListBeans.get(i).getBooksBeanList().size(); j++) {
            BookGroupBean bookGroupBean1 = new BookGroupBean();
            bookGroupBean1.setGroup(false);
            bookGroupBean1.setBookTime(bookListBeans.get(i).getBookTime());
            bookGroupBean1.setBooksBeanList(bookListBeans.get(i).getBooksBeanList().get(j));
            groupBeanList.add(bookGroupBean1);
        }
    }

    private void setGroupBeanListAll(int i, List<BookListBean> bookListBeans) {
        BookGroupBean bookGroupBean = new BookGroupBean();
        bookGroupBean.setGroup(true);
        bookGroupBean.setBookTime(bookListBeans.get(i).getBookTime());
        bookGroupBean.setPayInMoneyDay(bookListBeans.get(i).getPayInMoneyDay());
        bookGroupBean.setPayOutMoneyDay(bookListBeans.get(i).getPayOutMoneyDay());
        bookGroupBean.setPayInMoneyTotalMonthly(bookListBeans.get(i).getPayInMoneyTotalMonthly());
        bookGroupBean.setPayOutMoneyTotalMonthly(bookListBeans.get(i).getPayOutMoneyTotalMonthly());
        bookGroupBean.setPayInMoneyAnnualTotal(bookListBeans.get(i).getPayInMoneyAnnualTotal());
        bookGroupBean.setPayOutMoneyAnnualTotal(bookListBeans.get(i).getPayOutMoneyAnnualTotal());
        groupBeanList.add(bookGroupBean);
        setGroupBeanList(i, bookListBeans);
    }

    List<String> inviteList = new ArrayList<>();

    @Override
    public void onGetBookInfoSuccess(List<BookInfoBean> bookInfoBeans) {
        if (bookInfoBeans.size() > 0) {
            BookInfoBean bookInfoBean = bookInfoBeans.get(0);
            if (inviteList.size() > 0) {
                inviteList.clear();
            }
            List<Map<String, String>> invite = GsonUtils.fromJsonToListMaps(bookInfoBean.getUserInvite());
            for (Map<String, String> stringStringMap : invite) {
                inviteList.add(stringStringMap.get("userInvite"));
            }
            inviteList.add(0, "全部");

            bookTitleTxt.setText(bookInfoBean.getBookName());
            double budget = 0;
            if (bookInfoBean.getBookBudget() != null) {
                budget = (double) bookInfoBean.getBookBudget();
                mBudget = (String) bookInfoBean.getBookBudget();
            }
            String myBudget = StringUtils.formatNum(budget);
            bookBudgetMoney.setText(StringUtils.replaceNullByPstr(myBudget, "--"));
        }
    }


    @OnClick({R.id.book_more_img, R.id.book_time, R.id.book_xiala_img, R.id.book_in_money, R.id.book_out_money, R.id.book_budget_money
            , R.id.book_add, R.id.book_member, R.id.book_member_xiala_img})
    public void onClick(View view) {
        String money = null;
        switch (view.getId()) {
            case R.id.book_in_money:
                if (Utils.isFastClick(view)) {
                    if (groupBeanList.size() > 0) {
                        money = groupBeanList.get(0).getPayInMoneyTotalMonthly() + "";
                    }
                    showMoneyDialog(view, StringUtils.replaceNullByPstr(money, "--"));
                }
                break;
            case R.id.book_out_money:
                if (Utils.isFastClick(view)) {
                    if (groupBeanList.size() > 0) {
                        money = groupBeanList.get(0).getPayOutMoneyTotalMonthly() + "";
                    }
                    showMoneyDialog(view, StringUtils.replaceNullByPstr(money, "--"));
                }
                break;
            case R.id.book_budget_money:
                if (Utils.isFastClick(view)) {
                    showMoneyDialog(view, StringUtils.replaceNullByPstr(mBudget, "--"));
                }
                break;
            case R.id.book_more_img:
                if (Utils.isFastClick(view)) {
                    showMoreDialog(view);
                }
                break;
            case R.id.book_time:
            case R.id.book_xiala_img:
                if (Utils.isFastClick(view)) {
                    mDialogYearMonth.show(getActivity());
                }
                break;
            case R.id.book_add:
                if (Utils.isFastClick(view)) {
                    if (AppUserHelper.getInstance().getUser().getUserUseBook() != 0) {
                        startActivity(BookkeepingAddActivity.class);
                    } else {
                        ToastUtils.show("还没有账本，还无法添加账单！赶紧去创建账本吧！");
                    }
                }
                break;
            case R.id.book_member:
            case R.id.book_member_xiala_img:
                if (Utils.isFastClick(view)) {
                    DialogHelper.getInstance().showMenuDialog(getActivity(), inviteList, false, new DialogHelper.OnSelectedListener() {
                        @Override
                        public void onSelected(int position, String text) {
                            bookMember.setText(inviteList.get(position));
                            isRefresh = true;
                            page = 0;
                            page++;
                            if (AppUserHelper.getInstance().getUser().getUserUseBook() == 0) {
                                wbRefresh.finishRefresh();
                            } else {
                                mInvite = inviteList.get(position);
                                if (mInvite.equals("全部")) {
                                    mInvite = "";
                                } else {
                                    mInvite = inviteList.get(position);
                                }
                                mPresenter.getBookList(AppUserHelper.getInstance().getUser().getUserUseBook(),
                                        DateUtils.stringToFormat(bookTime.getText().toString()),
                                        page, mInvite);
                            }
                        }
                    });
                }
                break;
        }
    }

    private void showMoneyDialog(final View view, final String money) {
        new EasyDialog(getActivity(), R.layout.dialog_money_view) {
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                holder.setText(R.id.book_money, money);
            }
        }.backgroundLight(0.0)
                .setCanceledOnTouchOutside(true)
                .setCancelAble(true)
                .setCustomAnimations(AnimatorHelper.SlideInUp, AnimatorHelper.SlideOutDown)
                .setViewTop(view)
                .showDialog();
    }

    private void showMoreDialog(View view) {
        new EasyDialog(getActivity(), R.layout.dialog_more_view) {
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                holder.setOnClick(R.id.changer_book, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(BookManagerActivity.class);
                        dismiss();
                    }
                }).setOnClick(R.id.together_book, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                }).setOnClick(R.id.book_settings, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AppUserHelper.getInstance().getUser().getUserUseBook() != 0) {
                            BookEditActivity.startActivity(getActivity(), 2, 12);
                            dismiss();
                        } else {
                            ToastUtils.show("还没有账本哦！赶紧去创建账本吧！");
                        }
                    }
                }).setOnClick(R.id.book_import, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AppUserHelper.getInstance().getUser().getUserUseBook() != 0) {
                            startActivity(CSVImportActivity.class);
                            dismiss();
                        } else {
                            ToastUtils.show("还没有账本，还无法使用本功能哦！赶紧去创建账本吧！");
                        }
                    }
                });
            }
        }.backgroundLight(0.2)
                .setCanceledOnTouchOutside(true)
                .setCancelAble(true)
                .setCustomAnimations(AnimatorHelper.SlideInDown, AnimatorHelper.SlideOutUp)
                .setViewRighBottom(view)
                .showDialog();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDialogYearMonth != null) {
            mDialogYearMonth.clearDialog();
            mDialogYearMonth = null;
        }
    }

}
